#!/bin/sh

# waiting for pppoe connect
echo "waiting for pppoe connect"
sleep 10

# check if ss runing
if [ -n "`pidof ss-redir`" ]; then
        killall -9 ss-redir 2>/dev/null
fi
if [ -n "`pidof ss-tunnel`" ]; then
        killall -9 ss-tunnel 2>/dev/null
fi

#restart ss
echo `cat /etc/ss.conf`
ss-redir -c /etc/ss.conf -b 0.0.0.0 &
ss-tunnel -c /etc/ss.conf -b 0.0.0.0 -l 5353 -L 8.8.8.8:53 -u &

# check if ss runing
if [ -n "`pidof ss-redir`" ]; then
        echo "ss-redir start success..."
fi
# check if ss runing
if [ -n "`pidof ss-tunnel`" ]; then
        echo "ss-tunnel start success..."
fi

wget --quiet -O  /tmp/dnsmasq.d/dnsmasq_gfwlist_ipset.conf https://cokebar.github.io/gfwlist2dnsmasq/dnsmasq_gfwlist_ipset.conf

echo "dnsmasq_gfwlist_ipset.conf download success..."

#build ipset rules
ipset -N gfwlist iphash
iptables -t nat -A PREROUTING -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-port 1008
iptables -t nat -A OUTPUT -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-port 1008

# check if ss runing
if [ -n "`pidof dnsmasq`" ]; then
        killall -9 dnsmasq 2>/dev/null
fi

/usr/sbin/dnsmasq -C /var/etc/dnsmasq.conf -k -x /var/run/dnsmasq/dnsmasq.pid &

sleep 1

if [ -n "`pidof dnsmasq`" ]; then
        echo "dnsmasq start success..."
fi

